/*
 * @name: js封装的方法与请求
 * @version: 1.0
 * @author: zhiyong.li
 * @Date: 2020-07-20 10:26:19
 * @LastEditors: author
 * @LastEditTime: 2020-07-21 15:45:50
 */ 
var domaint = 'http://10.10.0.103:8080/tfw'// 请求的ip地址
layui.define(['form', 'jquery','layer','admin','table'], function (exports) { //提示：模块也可以依赖其它模块，如：layui.define('layer', callback);
  	let jQuery = layui.jquery,
		$ = jQuery,
		layer = layui.layer,
		table=layui.table,
		admin = layui.admin;
	//let domain = 'http://10.10.0.67:18086/tfw'// 请求的ip地址
	//let domain = 'http://192.168.10.108:18084/tfw';//zhang
	//let domain = 'http://192.168.10.106:18084/tfw'//yan
	//let domain = 'http://192.168.10.137:18084/tfw'//li
	//let domain = 'http://10.10.254.245:18084/tfw'//zmt
	//let domain = 'http://10.10.254.244:18084/tfw'
	//let domain = 'http://127.0.0.1:18084/tfw'
	let domain = domaint;

	let api = {
		loginPost: loginPost,
		ajaxPost: ajaxPost,
		ajaxGet: ajaxGet,
		ajaxPut:ajaxPut,
		ajaxGetexcel:ajaxGetexcel,
		ajaxGetword:ajaxGetword,
		domain:domain,
		ajaxGetindex:ajaxGetindex
	}
	  /**
	   * 
	   * @name: 登录
	   * @param { url } 请求地址
	   * @param { data } 请求数据
	   */
	function loginPost(url,data = {}) {
		return new Promise((resolve,reject) => {
			$.ajax({ 
				url: domain + url,
				data: JSON.stringify(data),
				type: 'POST',
				dataType: 'json',
				headers: {
					"Content-Type": 'application/json;charset=utf8',
				},
				success: (res) => {
					resolve(res);
				},
				error: (err) => {
					reject(err);
				}
			})
		})
	} 
	/**
	* @name: post请求
	* @param { url } 请求地址
	* @param { data } 请求数据
	*/
	function ajaxPost(url,data = {}) {
		let timestamp = new Date().getTime(); // 时间戳
		let sign = calculateSign('POST',timestamp,data); // 生成签名
		return new Promise((resolve,reject) => {
			$.ajax({
				url: domain + url,
				data: JSON.stringify(data),
				type: 'POST',
				dataType: 'json',
				async:'flase',
				headers: {
					"Content-Type": 'application/json;charset=utf8',
					timestamp: timestamp,
					sign: sign,
					Authorization: localStorage.getItem('Authorization')
				},
				success: (res) => {
					if(res.code == 601){
						top.layer.open({
							id: 'xlogin',
							type: 2,
							maxmin: true,
							title: false,
							closeBtn: 0,
							area: ['100%', '100%'],
							content: ['../Account/Xlogin.html', 'no'],
							success: function (layero, index) {
								layero.find(".layui-layer-setwin").remove();
								layero.find(".layui-layer-ico layui-layer-close layui-layer-close2").remove();
							}
						});	
						return false;
					}else{
						resolve(res);
						refersh();
					}
				},
				error: (err) => {
					reject(err);
				}
			})
		})
	}
	
	/**
	* @name: get请求
	* @param { url } 请求地址
	* @param { data } 请求数据
	*/
	function ajaxGet(url,data = {}) {
		let timestamp = new Date().getTime(); // 时间戳
		let sign = calculateSign('GET',timestamp,data);
		return new Promise((resolve,reject) => {
			$.ajax({
				url: domain + url,
				data: data,
				type: 'GET',
				dataType: 'json',
				async:'true',
				headers: {
					contentType: 'application/json;charset=utf8',
					timestamp: timestamp,
					sign: sign,
					Authorization: localStorage.getItem('Authorization')
				},
				success: (res) => {
					if(res.code == 601){
						top.layer.open({
							id: 'xlogin',
							type: 2,
							maxmin: true,
							title: false,
							closeBtn: 0,
							area: ['100%', '100%'],
							content: ['../Account/Xlogin.html', 'no'],
							success: function (layero, index) {
								layero.find(".layui-layer-setwin").remove();
								layero.find(".layui-layer-ico layui-layer-close layui-layer-close2").remove();
							}
						});	
						return false;
					}else{
						resolve(res);
						refersh();
					}
				},
				error: (err) => {
					reject(err);
				}
			})
		})
	}
	function ajaxGetindex(url,data = {}) {
		let timestamp = new Date().getTime(); // 时间戳
		let sign = calculateSign('GET',timestamp,data);
		return new Promise((resolve,reject) => {
			$.ajax({
				url: domain + url,
				data: data,
				type: 'GET',
				dataType: 'json',
				async:'flase',
				headers: {
					contentType: 'application/json;charset=utf8',
					timestamp: timestamp,
					sign: sign,
					Authorization: localStorage.getItem('Authorization')
				},
				success: (res) => {
					if(res.code == 601 || res.code == 500){
						layer.alert("您的登录已过期，请重新登录", {closeBtn: 0 }, function (index) { 
							layer.close(index);
							window.location.href = "../../Views/Account/Login.html";		 
						});
					}else{
						resolve(res);
						refersh();
					}
				},
				error: (err) => {
					reject(err);
				}
			})
		})
	}
	/**
	* @name: 生成签名
	* @param { type } 请求类型
	* @param { timestamp } 时间戳
	* @param { data } 请求数据
	* @return: 返回类型
	*/
	function calculateSign(type,timestamp,data) {
		let secretKey = '123456789'; // 密钥
		let d = dataFormat(type,data); // 格式化的数据
		return sha256(secretKey + timestamp + d);	
	}

	/**
	* @name: 请求api数据格式化
	* @param { type } 请求数据的类型
	* @param { data } 需要格式化的数据
	* @return: 序列化数据
	*/
	function dataFormat(type,data) {
		if(type === 'POST') {
			return JSON.stringify(data);
		}else if(type === 'GET') {
			const names = Object.keys(data).sort()
			let ret = ''
			for (let i = 0; i < names.length; ++i) {
				const name = names[i]
				const val = data[name]
				if (val === false) {
					ret += (name + '0')
				} else if (val === true) {
					ret += (name + '1')
				} else if (typeof val === 'number') {
					ret += (name + val)
				} else if (typeof val === 'string') {
					ret += (name + val)
				} else if (Array.isArray(val)) {
				// Array 只能是Number 和 String
				// 其中String是不需要URL编码的
					ret += (name + val.join(','))
				} else if(val){
					ret += (name + JSON.stringify(val))
				} else {
					ret += name
				}
			}
			return ret;
		}else if(type === 'PUT') {
			return JSON.stringify(data);
		}
	}	
	/**
	* @name: PUT请求
	* @param { url } 请求地址
	* @param { data } 请求数据
	*/
	function ajaxPut(url,data = {}) {
		let timestamp = new Date().getTime(); // 时间戳
		let sign = calculateSign('PUT',timestamp,data); // 生成签名
		return new Promise((resolve,reject) => {
			$.ajax({
				url: domain + url,
				data: JSON.stringify(data),
				type: 'PUT',
				dataType: 'json',
				headers: {
					"Content-Type": 'application/json;charset=utf8',
					timestamp: timestamp,
					sign: sign,
					Authorization: localStorage.getItem('Authorization')
				},
				success: (res) => {
					if(res.code == 601){
						top.layer.open({
							id: 'xlogin',
							type: 2,
							maxmin: true,
							title: false,
							closeBtn: 0,
							area: ['100%', '100%'],
							content: ['../Account/Xlogin.html', 'no'],
							success: function (layero, index) {
								layero.find(".layui-layer-setwin").remove();
								layero.find(".layui-layer-ico layui-layer-close layui-layer-close2").remove();
							}
						});	
					}else{
						resolve(res);
						refersh();
					}
				},
				error: (err) => {
					reject(err);
				}
			})
		})
	}

	/**
	* @name: Get导出excel请求
	* @param { url } 请求地址
	* @param { data } 请求数据
	*/
	function ajaxGetexcel(url,name) {
		var loadindex = layer.load();
		var index = url.indexOf('?')+1;
		
		var str = url.substring(index);
		var arr = str.split('&');
		var obj={};
		for(var i =0;i<arr.length;i++){
			var str1 = arr[i].split('=')[0];
			var str2 = arr[i].split('=')[1];
			obj[str1] = str2;
		}
		let timestamp = new Date().getTime(); // 时间戳
		if(index==0){
			obj={};
		}
		let sign = calculateSign('GET',timestamp,obj);
		var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = "blob";
        xhr.setRequestHeader("timestamp", timestamp);
        xhr.setRequestHeader("sign", sign);
        xhr.setRequestHeader("Authorization", localStorage.getItem('Authorization'));
        xhr.onload = function () {
            if (this.status === 200) {
                let data = this.response;
                let fileReader = new FileReader();
                fileReader.onload = function() {
                    try {
                        let jsonData = JSON.parse(this.result);  // 说明是普通对象数据，后台转换失败
                        if (jsonData.code) {
                            if(jsonData.code == 500){
                                layer.close(loadindex);
                                layer.msg("导出失败："+jsonData.msg);
                                return false;  
                            }
                        }
                    } catch (err) {
                        fileReader.readAsDataURL(data);    // 转换为base64，可以直接放入a表情href
                        fileReader.onload = function (e) {
							var a = document.createElement('a');
                            a.download = name+'.xls';
                            a.href = e.target.result;
                            $("body").append(a);
                            a.click();
                            $(a).remove();
                            layer.close(loadindex);
                        }
                    } 
                };
				fileReader.readAsText(data);
				refersh();
            }else{
                layer.close(loadindex);
                layer.msg("导出失败");
                return false;
            }
		};
		xhr.send();
	}
	/**
	* @name: Get导出word请求
	* @param { url } 请求地址
	* @param { data } 请求数据
	*/
	function ajaxGetword(url,name) {
		var loadindex = layer.load();
		var index = url.indexOf('?')+1;
		var str = url.substring(index);
		var arr = str.split('&');
		var obj={};
		for(var i =0;i<arr.length;i++){
			var str1 = arr[i].split('=')[0];
			var str2 = arr[i].split('=')[1];
			obj[str1] = str2;
		}
		let timestamp = new Date().getTime(); // 时间戳
		let sign = calculateSign('GET',timestamp,obj);
		var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = "blob";
        xhr.setRequestHeader("timestamp", timestamp);
        xhr.setRequestHeader("sign", sign);
        xhr.setRequestHeader("Authorization", localStorage.getItem('Authorization'));
        xhr.onload = function () {
            if (this.status === 200) {
                let data = this.response;
                let fileReader = new FileReader();
                fileReader.onload = function() {
                    try {
                        let jsonData = JSON.parse(this.result);  // 说明是普通对象数据，后台转换失败
                        if (jsonData.code) {
                            if(jsonData.code == 500){
                                layer.close(loadindex);
                                layer.msg("导出失败："+jsonData.msg);
                                return false;  
                            }
                        }
                    } catch (err) {
                        fileReader.readAsDataURL(data);    // 转换为base64，可以直接放入a表情href
                        fileReader.onload = function (e) {
							var a = document.createElement('a');
                            a.download = name+'.doc';
                            a.href = e.target.result;
                            $("body").append(a);
                            a.click();
                            $(a).remove();
                            layer.close(loadindex);
                        }
                    } 
                };
				fileReader.readAsText(data);
				layer.close(loadindex);
				refersh();
            }else{
                layer.close(loadindex);
                layer.msg("导出失败");
                return false;
            }
		};
		xhr.send();
	}
	exports('api',api);
})
var url = document.location.pathname;
if(url !="/Views/Account/Login.html"){
	var token = localStorage.getItem('Authorization');
	if(token == "null" || token == null){
		window.location.href = "../../Views/Account/Login.html";
	}	
}
//表格方法
function calculateSigntable(type,timestamp,data) {
	let secretKey = '123456789'; // 密钥
	let d = dataFormatr(type,data); // 格式化的数据
	return sha256(secretKey + timestamp + d);	
}
function dataFormatr(type,data) {
	if(type === 'post') {
		return JSON.stringify(data);
	}else if(type === 'get') {
		const names = Object.keys(data).sort()
		let ret = ''
		for (let i = 0; i < names.length; ++i) {
			const name = names[i]
			const val = data[name]
			if (val === false) {
				ret += (name + '0')
			} else if (val === true) {
				ret += (name + '1')
			} else if (typeof val === 'number') {
				ret += (name + val)
			} else if (typeof val === 'string') {
				ret += (name + val)
			} else if (Array.isArray(val)) {
			// Array 只能是Number 和 String
			// 其中String是不需要URL编码的
				ret += (name + val.join(','))
			} else if(val){
				ret += (name + JSON.stringify(val))
			} else {
				ret += name
			}
		}
		return ret;
	}	
}
//单位方法	
function calculateSigndepart(type,timestamp) {
	let secretKey = '123456789'; // 密钥
	return sha256(secretKey + timestamp);	
}
function refersh(){
	let timestamp = new Date().getTime(); // 时间戳
	let sign = calculateSigntable('get',timestamp,'');
	var xhr = new XMLHttpRequest();
	xhr.open('get', domaint + "/userLogin/refresh", true);
	//xhr.responseType = "json";
	xhr.setRequestHeader("timestamp", timestamp);
	xhr.setRequestHeader("sign", sign);
	xhr.setRequestHeader("Authorization", localStorage.getItem('Authorization'));
	xhr.onload = function () {
	
	};
	xhr.send();
	xhr.onreadystatechange = function(){
		if(xhr.readyState == 4 && xhr.status == 200){
			var data=JSON.parse(xhr.responseText);
			localStorage.setItem('Authorization', data.data.token);
		}
	}
}